package club.beimeng.emailserver2.aop.log;

import lombok.Data;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Logger;


@Aspect
@Component
public class AopLogger {

    private Logger logger = Logger.getLogger("处理请求");

    /**
     * 定义切入点
     */
    @Pointcut("execution(public * club.beimeng.emailserver2.controller.*.*(..))")
    public void webLog(){}

    private Date date;

    /**
     * 前置通知：在连接点之前执行的通知
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        date = new Date();
        // 记录下请求内容
        logger.info( "id" + date.getTime() + " | "
                + "IP : " + request.getRemoteAddr() + " | "
                + "HTTP_METHOD : " + request.getMethod() + " | "
                + "ARGS : " + Arrays.toString(joinPoint.getArgs()) + " | "
                + "CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + " | "
                + "URL : " + request.getRequestURL().toString()
        );
    }

    @AfterReturning(returning = "ret",pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + "id" + date.getTime() + " | " + ret);
    }
}
